package com.zzz.offer;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 1. 找出数组中重复的数字
 * 2.
 */
public class OfferStudyApplication {
    static Map<Integer, String> TOPIC = new HashMap<>();
    static Map<Integer,Object[]> PARAMS = new HashMap<>();
    static {
        TOPIC.put(1, "findRepeatNumberInArray");
        PARAMS.put(1, new Object[]{new Integer[]{1, 2, 3, 4, 0}});
    }

    public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
        Integer target = 1;
        System.out.println(execute(TOPIC.get(target), PARAMS.get(target)));
    }

    private static Object execute(String method, Object[] param) throws InvocationTargetException, IllegalAccessException {
        Method[] declaredMethods = OfferStudyApplication.class.getDeclaredMethods();
        OfferStudyApplication offerStudyApplication = new OfferStudyApplication();
        for (Method declaredMethod : declaredMethods) {
            if (declaredMethod.getName().equals(method)) {
                return declaredMethod.invoke(offerStudyApplication, param);
            }
        }
        throw new RuntimeException("no method");
    }

    /**
     * 1. 找出数组中重复的数字
     * 给定一个长度为 n 的整数数组 nums，数组中所有的数字都在 0∼n−1 的范围内。
     * 数组中某些数字是重复的，但不知道有几个数字重复了，也不知道每个数字重复了几次。
     * 请找出数组中任意一个重复的数字。
     * @param arrays
     * @return
     */
    private Object findRepeatNumberInArray(Integer[] arrays) {
        if (arrays == null) {
            return -1;
        }
        for (int i = 0; i < arrays.length - 1; i++) {
            int indexIni = arrays[arrays[0]];
            int indexInZero = arrays[0];
            if (indexIni == indexInZero) {
                return arrays[0];
            } else {
                //不相等交换
                int temp = indexIni ^ indexInZero;
                arrays[arrays[0]] = temp ^ indexIni;
                arrays[0] = temp ^ indexInZero;
            }
        }
        return -1;
    }

}
